//
//  YBImRoomSmallView.m
//  iphoneLive
//
//  Created by YB007 on 2022/6/17.
//  Copyright © 2022 cat. All rights reserved.
//

#import "YBImRoomSmallView.h"

#import "TConversationCell.h"
#import "THeader.h"
#import "TUIKit.h"
#import "TChatC2CController.h"

#import "MessageListModel.h"
#import "MessageFansVC.h"
#import "MsgTopPubVC.h"
#import "SelPeopleV.h"
#import "JCHATAlertViewWait.h"
#import "MsgSysVC.h"
#import "OrderMessageVC.h"


@interface YBImRoomSmallView()<UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,V2TIMConversationListener>{
    dispatch_group_t _imgListGroup;
    SelPeopleV * _selV;
    
    TConversationCellData *conver_admin1;//官方通知
    TConversationCellData *conver_admin2;//系统通知
    TConversationCellData *_conversation_fans;       //顶部-粉丝
    TConversationCellData *_conversation_zan;        //顶部-赞
    TConversationCellData *_conversation_at;         //顶部-@
    TConversationCellData *_conversation_comment;    //顶部-评论
    
    TConversationCellData *_conversation_ctr;        //风控管理员
    TConversationCellData *_conversation_goodsorder;
    TConversationCellData *_conversation_hostid;
    
    CGFloat _smallViewHeight;
    BOOL _stopTap;

}
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UILabel *topTitleL;
@property(nonatomic,strong)UIButton *topIgnoreBtn;
@property(nonatomic,strong)UIButton *topLeftBtn;

///IM列表
@property(nonatomic,strong)NSString *liveUid;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *data;

///C2C
@property(nonatomic,strong)UIView *c2cBgView;
@property(nonatomic,strong)MsgSysVC *c2cSysVC;
@property(nonatomic,strong)TChatC2CController *c2cChatVC;

@end

@implementation YBImRoomSmallView

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch; {
    if ([touch.view isDescendantOfView:self.bgView]) {
        return NO;
    }
    return YES;
}
-(void)dissmissView {
    if (_stopTap) {
        [self endEditing:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:ybImSamllChange object:@(0)];
        [_c2cChatVC.inputController hideFaceAnimation];
        return;
    }
    if (_imSmallType == ImSmall_List && _c2cBgView.hidden == NO) {
        [self changeTopDesWithData:nil];
    }else{
        if (self.imCtrEvent) {
            self.imCtrEvent(ImCtr_Dismiss, @{});
        }
        [self removeNoti];
    }
}

+(instancetype)showImListWithLiveUid:(NSString *)liveuid;{
    YBImRoomSmallView *view = [[YBImRoomSmallView alloc]init];
    view.liveUid = liveuid;
    view.frame = CGRectMake(0, 0, _window_width, _window_height);
    [[YBBaseAppDelegate sharedAppDelegate].topViewController.view addSubview:view];
    [view createUI];
    return view;
}
-(void)createUI {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dissmissView)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
    
    _smallViewHeight = _window_height*0.45;
    [self addNoti];
    self.backgroundColor = RGB_COLOR(@"#000000", 0.1);
    
    _bgView = [[UIView alloc]init];
    _bgView.backgroundColor = UIColor.whiteColor;
    [self addSubview:_bgView];
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.bottom.centerX.equalTo(self);
        make.height.mas_equalTo(_smallViewHeight+44);
    }];
    
    UIView *topNav = [[UIView alloc]init];
    [_bgView addSubview:topNav];
    [topNav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.centerX.top.equalTo(_bgView);
        make.height.mas_equalTo(44);
    }];
    UILabel *topTitleL = [[UILabel alloc]init];
    topTitleL.text = YZMsg(@"消息");
    topTitleL.font = NaviTitle_Font;
    topTitleL.textColor = RGB_COLOR(@"#323232", 1);
    [topNav addSubview:topTitleL];
    self.topTitleL = topTitleL;
    [topTitleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(topNav);
    }];
    UIButton *ignoreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ignoreBtn setTitle:YZMsg(@"忽略未读") forState:0];
    ignoreBtn.titleLabel.font = SYS_Font(13);
    [ignoreBtn setTitleColor:RGB_COLOR(@"#969696", 1) forState:0];
    [ignoreBtn addTarget:self action:@selector(clickIgnoreBtn) forControlEvents:UIControlEventTouchUpInside];
    [topNav addSubview:ignoreBtn];
    self.topIgnoreBtn = ignoreBtn;
    [ignoreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.centerY.equalTo(topNav);
        make.right.equalTo(topNav.mas_right).offset(-10);
    }];
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:[UIImage imageNamed:@"gray_back"] forState:0];
    [leftBtn addTarget:self action:@selector(clickLeftBtn) forControlEvents:UIControlEventTouchUpInside];
    [topNav addSubview:leftBtn];
    leftBtn.hidden = YES;
    self.topLeftBtn = leftBtn;
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topNav);
        make.width.height.mas_equalTo(40);
        make.left.equalTo(topNav.mas_left).offset(0);
    }];
    
    ///
    _data = [NSArray array];
    _imgListGroup = dispatch_group_create();
   
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = UIColor.whiteColor;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = 0;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, ShowDiff, 0);
    [_bgView addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topNav.mas_bottom);
        make.width.centerX.bottom.equalTo(_bgView);
    }];
    if (@available(iOS 11.0,*)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    ///
    [_bgView addSubview:self.c2cBgView];
    [_c2cBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerX.centerY.equalTo(_tableView);
    }];
    [_bgView layoutIfNeeded];
    
}
- (void)setImSmallType:(ImSmallType)imSmallType{
    _imSmallType = imSmallType;
    if (_imSmallType == ImSmall_List) {
        [self pullListData];
    }
}
-(void)changeTopDesWithData:(TConversationCellData*)cellData {
    if (cellData) {
        self.topTitleL.text = cellData.userName;
        self.topIgnoreBtn.hidden = YES;
        self.topLeftBtn.hidden = NO;
        _c2cBgView.hidden = NO;
    }else{
        self.topTitleL.text = YZMsg(@"消息");
        self.topIgnoreBtn.hidden = NO;
        self.topLeftBtn.hidden = YES;
        _c2cBgView.hidden = YES;
        _c2cSysVC.listModel = nil;
        [self destroyVCView];
    }
}
#pragma mark - IM列表开始

-(void)clickLeftBtn {
    [self dissmissView];
}
-(void)pullListData {
    [self updateConversations];
}
-(void)clearUnreadNum {
    for (int i = 0; i < _data.count; i ++) {
        TConversationCellData *data = _data[i];
        data.unRead = 0;
        NSMutableArray *new_a = [NSMutableArray arrayWithArray:_data];
        [new_a replaceObjectAtIndex:i withObject:data];
        _data = [NSArray arrayWithArray:new_a];
    }
    [_tableView reloadData];
}

- (void)clickIgnoreBtn {
    int unread = 0;
    for (TConversationCellData *conversation in _data){
        unread += conversation.unRead;
        [[YBImManager shareInstance] clearUnreadConvId:conversation.convId sendNot:NO];
    }
    unread += _conversation_ctr.unRead;
    [[YBImManager shareInstance] clearUnreadConvId:_conversation_ctr.convId sendNot:NO];
    if (unread == 0) {
        [MBProgressHUD showPop:YZMsg(@"当前暂无未读消息")];
    }else {
        [MBProgressHUD showPop:YZMsg(@"已经忽略未读消息")];
        [self updateConversations];
    }
}
-(void)addNoti {
    [self removeNoti];
    NSNotificationCenter *notCenter = [NSNotificationCenter defaultCenter];
//    [notCenter addObserver:self selector:@selector(onRefreshConversations:) name:TUIKitNotification_TIMRefreshListener object:nil];
    [[V2TIMManager sharedInstance] addConversationListener:self];

    [notCenter addObserver:self selector:@selector(imInputHeightChange:) name:ybImSamllChange object:nil];
}
#pragma mark --消息监听
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
    [self updateConversations];
}

-(void)imInputHeightChange:(NSNotification *)not {
    CGFloat changeHeight =  [not.object floatValue];
    _stopTap = NO;
    if (changeHeight>0) {
        _stopTap = YES;
    }
    [_bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.width.bottom.centerX.equalTo(self);
        make.height.mas_equalTo(_smallViewHeight+44+changeHeight);
    }];
    [_c2cBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_bgView.mas_top).offset(44);
        make.width.centerX.bottom.equalTo(_bgView);
    }];
    [_bgView layoutIfNeeded];
    [_c2cBgView layoutIfNeeded];
    NSLog(@"rk=========================rk_smallim:%f",changeHeight);
    _c2cChatVC.view.frame = CGRectMake(0, 0, _window_width, _smallViewHeight+changeHeight);
    [_c2cChatVC changeSmallHeight];
}
-(void)removeNoti {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc {
    [self removeNoti];
}
- (void)onRefreshConversations:(NSNotification *)notification {
    //NSLog(@"xxxxxxokokokokokoko");
    [self updateConversations];
}
- (void)updateConversations{
    YBWeakSelf;
    [[YBImManager shareInstance]getAllConversationList:^(NSMutableArray *CovList, BOOL isSuccess) {
            if(isSuccess){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf goReload:CovList];
                });
            }
    }];

//    [[YBImManager shareInstance] getLastDisplayStringWith:_imgListGroup finish:^(NSArray *transformArray) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf goReload:transformArray];
//        });
//    }];
}
-(void)goReload:(NSArray *)reloadA {
    
    NSSortDescriptor * sortDes = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    NSArray *sortResult = [reloadA sortedArrayUsingDescriptors:@[sortDes]];
    NSMutableArray *m_group_array = [NSMutableArray array];
    NSMutableArray *m_c2c_array = [NSMutableArray array];
    for (TConversationCellData *sortData in sortResult) {
        if(sortData.convType == TConv_Type_Group){
            [m_group_array addObject:sortData];
        }else if (sortData.convType == TConv_Type_C2C){
            NSString *imName = sortData.convId;
            if ([imName isEqual:@"dsp_admin_1"]) {
                //
                conver_admin1 = sortData;
            }else if ([imName isEqual:@"dsp_admin_2"]){
                //
                conver_admin2 = sortData;
            }else if ([imName isEqual:@"dsp_fans"]) {
                //粉丝
                _conversation_fans = sortData;
            }else if ([imName isEqual:@"dsp_like"]){
                //赞
                _conversation_zan = sortData;
            }else if ([imName isEqual:@"dsp_at"]){
                //@
                _conversation_at = sortData;
            }else if ([imName isEqual:@"dsp_comment"]){
                //评论
                _conversation_comment = sortData;
            }else if ([imName isEqual:@"dsp_admin_control"]){
                //风控管理员
                _conversation_ctr = sortData;
            }else if ([imName isEqual:@"goodsorder_admin"]){
                //订单管理员【未要求具体排序这里add即可】
                _conversation_goodsorder = sortData;
            }else if([imName containsString:@"dsp_user_"]){
                // dsp_user_live 【用于推送】
                
            }else if ([imName isEqual:_liveUid]){
                // 主播
                _conversation_hostid = sortData;
            }
            else{
                [m_c2c_array addObject:sortData];
            }
        }
    }
    // 检查dsp_admin_2 、主播是否缺失
    if (!conver_admin2) {
        conver_admin2 = [[YBImManager shareInstance] createEmptyCellDataWithId:@"dsp_admin_2"];
    }
    if (!_conversation_hostid && ![_liveUid isEqual:[Config getOwnID]]) {
        _conversation_hostid = [[YBImManager shareInstance] createEmptyCellDataWithId:_liveUid];
    }
    // 风控未读叠加到系统消息
    if (_conversation_ctr) {
        conver_admin2.unRead += _conversation_ctr.unRead;
    }
    [m_c2c_array insertObject:_conversation_hostid atIndex:0];
    [m_c2c_array insertObject:conver_admin2 atIndex:0];
    
    [self requestUserMessage:[m_c2c_array mutableCopy]];
}

- (void)requestUserMessage:(NSArray *)msgArray{
    NSString *uids = @"";
    for (TConversationCellData *data in msgArray) {
        uids = [uids stringByAppendingFormat:@"%@,",data.convId];
    }
    if (uids.length > 0) {
        //去掉最后一个逗号
        uids = [uids substringToIndex:[uids length] - 1];
    }
    NSMutableArray *m_array = [NSMutableArray array];
    [WYNetworking postWithUrl:[NSString stringWithFormat:@"User.getMultiInfo&uids=%@",uids] Dic:@{} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            for (int i = 0; i < [info count]; i ++) {
                NSDictionary *plantSubDic = info[i];
                for (TConversationCellData *data in msgArray) {
                    if ([data.convId isEqual:strFormat([plantSubDic valueForKey:@"id"])]) {
                        [data updateUserInfo:plantSubDic];
                        [m_array addObject:data];
                    }
                }
            }
            _data = [NSArray arrayWithArray:m_array];
            [_tableView reloadData];
        }
    } Fail:^(id fail) {
        
    }];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [TConversationCell getSize].height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row>1) {
        return YES;
    }
    return NO;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YZMsg(@"删除");
}
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    TConversationCellData *conv = _data[indexPath.row];
    NSMutableArray *new_a = [NSMutableArray arrayWithArray:_data];
    [new_a removeObjectAtIndex:indexPath.row];
    _data = [NSArray arrayWithArray:new_a];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
 
    [[YBImManager shareInstance]clearUnreadConvId:conv.convId sendNot:YES];
    NSString *userid = [NSString stringWithFormat:@"c2c_%@",conv.convId];
    [[V2TIMManager sharedInstance] deleteConversation:userid succ:^{
        NSLog(@"success");
    } fail:^(int code, NSString *desc) {
        NSLog(@"failure, code:%d, desc:%@", code, desc);
    }];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:TUIKitNotification_TIMCancelunread object:nil];
//    });
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    TConversationCellData *conversation = [_data objectAtIndex:indexPath.row];
    [self goChatWithC2CWithConv:conversation];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TConversationCell *cell  = [tableView dequeueReusableCellWithIdentifier:TConversationCell_ReuseId];
    if(!cell){
        cell = [[TConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TConversationCell_ReuseId];
    }
    TConversationCellData *celldata =[_data objectAtIndex:indexPath.row];
    // 改变UI
    [cell imsmallViewResetUI];
    [cell setData:celldata];
    [cell checkImRecordWithHostid:_liveUid];
    return cell;
}
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}
#pragma mark - IM列表结束


#pragma mark - IM C2C 开始
-(void)goChatWithC2CWithConv:(TConversationCellData *)conversation {
    [self destroyVCView];
    // 改变标题
    [self changeTopDesWithData:conversation];
    
    [[YBImManager shareInstance] clearUnreadConvId:conversation.convId sendNot:YES];
    if ([conversation.convId isEqual:@"dsp_admin_1"]||[conversation.convId isEqual:@"dsp_admin_2"]) {
        if ([conversation.convId isEqual:@"dsp_admin_2"]) {
            [[YBImManager shareInstance] clearUnreadConvId:_conversation_ctr.convId sendNot:NO];
        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:conversation.userHeader forKey:@"avatar"];
        [dic setObject:conversation.convId forKey:@"id"];
        [dic setObject:conversation.userName forKey:@"user_nickname"];
        //[dic setObject:conversation.lastConv forKey:@"conversation"];
        MessageListModel *model = [MessageListModel modelWithDictionary:dic];
        
        [_c2cBgView addSubview:[self c2cSysView]];
        _c2cSysVC.view.frame = CGRectMake(0, 0, _window_width, _smallViewHeight);
        _c2cSysVC.listModel = model;
        [_c2cSysVC imSmallViewReload];
    }
    else{
        [_c2cBgView addSubview:[self c2cChatView]];
        _c2cChatVC.view.frame = CGRectMake(0, 0, _window_width, _smallViewHeight);
        _c2cChatVC.conversation = conversation;
        [_c2cChatVC imSmallViewReload];
    }
    
}
-(void)destroyVCView {
    if (_c2cSysVC) {
        [_c2cSysVC.view removeFromSuperview];
        _c2cSysVC = nil;
    }
    if (_c2cChatVC) {
        [_c2cChatVC.view removeFromSuperview];
        _c2cChatVC = nil;
    }
}
- (UIView *)c2cBgView{
    if (!_c2cBgView) {
        _c2cBgView = [[UIView alloc]init];
        _c2cBgView.backgroundColor = UIColor.whiteColor;
        _c2cBgView.hidden = YES;
    }
    return _c2cBgView;
}
- (UIView *)c2cSysView {
    if (!_c2cSysVC) {
        _c2cSysVC = [[MsgSysVC alloc]init];
        _c2cSysVC.uiFrom = UiFrom_Samll;
        _c2cSysVC.isWhiteStyle = YES;
    }
    return _c2cSysVC.view;
}
- (UIView *)c2cChatView{
    if (!_c2cChatVC) {
        _c2cChatVC = [[TChatC2CController alloc]init];
        _c2cChatVC.uiFrom = UiFrom_Samll;
    }
    return _c2cChatVC.view;
}
#pragma mark - IM C2C 结束
@end
